<template>
  <view class="order-page">
    <nav-header title="订单记录"></nav-header>
    
    <view class="content" :style="{ paddingTop: statusBarHeight + 44 + 'px' }">
      <!-- Tabs -->
      <view class="tabs">
        <view 
          class="tab-item" 
          v-for="(tab, index) in tabs" 
          :key="index"
          :class="{ 'active': activeTab === tab.value }"
          @click="activeTab = tab.value"
        >
          <text>{{ tab.label }}</text>
        </view>
      </view>
      
      <!-- Orders List -->
      <view class="orders-list" v-if="filteredOrders.length > 0">
        <view 
          class="order-item" 
          v-for="(order, index) in filteredOrders" 
          :key="index"
        >
          <view class="order-header">
            <text class="order-no">订单号：{{ order.orderNo }}</text>
            <text class="order-status" :class="getStatusClass(order.status)">{{ getStatusText(order.status) }}</text>
          </view>
          
          <view class="order-products">
            <view class="product-item" v-for="(product, idx) in order.products" :key="idx">
              <image class="product-image" :src="product.image" mode="aspectFill"></image>
              <view class="product-info">
                <text class="product-name">{{ product.name }}</text>
                <text class="product-desc">{{ product.description }}</text>
              </view>
              <text class="product-price">¥{{ product.price.toFixed(2) }}</text>
            </view>
          </view>
          
          <view class="order-footer">
            <view class="order-meta">
              <text class="order-time">{{ formatDate(order.createdAt) }}</text>
              <text class="order-total">总计：¥{{ getOrderTotal(order).toFixed(2) }}</text>
            </view>
            <view class="order-actions">
              <view class="action-btn detail-btn" @click="viewOrderDetail(order.id)">
                <text>查看详情</text>
              </view>
              <view class="action-btn" v-if="order.status === 'pending'" @click="payOrder(order.id)">
                <text>去支付</text>
              </view>
              <view class="action-btn" v-if="order.status === 'shipped'" @click="confirmReceipt(order.id)">
                <text>确认收货</text>
              </view>
            </view>
          </view>
        </view>
      </view>
      
      <!-- Empty State -->
      <view class="empty-state" v-else>
        <image class="empty-icon" src="/static/images/empty-order.png" mode="aspectFit"></image>
        <text class="empty-text">暂无订单记录</text>
        <view class="browse-btn" @click="navigateToTemplates">
          <text>去升级会员</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useUserStore } from '@/store/user.js'
import NavHeader from '@/components/nav-header.vue'

const userStore = useUserStore()
const statusBarHeight = ref(20)
const activeTab = ref('all')
const ordersList = ref([])

// 标签页
const tabs = [
  { label: '全部', value: 'all' },
  { label: '待付款', value: 'pending' },
  { label: '已付款', value: 'paid' },
  { label: '已发货', value: 'shipped' },
  { label: '已完成', value: 'completed' }
]

// 根据当前选中的标签过滤订单
const filteredOrders = computed(() => {
  if (activeTab.value === 'all') {
    return ordersList.value
  } else {
    return ordersList.value.filter(order => order.status === activeTab.value)
  }
})

onMounted(() => {
  // 获取状态栏高度
  const systemInfo = uni.getSystemInfoSync()
  statusBarHeight.value = systemInfo.statusBarHeight
  
  // 加载订单列表
  loadOrders()
})

// 加载订单列表
const loadOrders = () => {
  // 从Store获取订单
  const storeOrders = userStore.getOrders() || []
  
  // 如果为空，添加示例数据（仅用于演示）
  if (storeOrders.length === 0 && process.env.NODE_ENV === 'development') {
    ordersList.value = [
      {
        id: '1',
        orderNo: 'ORD202504100001',
        status: 'paid',
        createdAt: new Date('2025-04-10T15:30:00'),
        products: [
          {
            id: '101',
            name: 'VIP会员月卡',
            description: '30天VIP会员服务',
            price: 28.00,
            image: '/static/images/vip-month.png'
          }
        ]
      },
      {
        id: '2',
        orderNo: 'ORD202503250002',
        status: 'completed',
        createdAt: new Date('2025-03-25T09:15:00'),
        products: [
          {
            id: '102',
            name: '简历导出服务',
            description: '一次性简历PDF导出',
            price: 9.90,
            image: '/static/images/resume-export.png'
          }
        ]
      },
      {
        id: '3',
        orderNo: 'ORD202504180003',
        status: 'pending',
        createdAt: new Date('2025-04-18T18:20:00'),
        products: [
          {
            id: '103',
            name: 'VIP会员年卡',
            description: '365天VIP会员服务，尊享所有特权',
            price: 198.00,
            image: '/static/images/vip-year.png'
          }
        ]
      }
    ]
  } else {
    ordersList.value = storeOrders
  }
}

// 获取订单状态显示文本
const getStatusText = (status) => {
  const statusMap = {
    'pending': '待付款',
    'paid': '已付款',
    'shipped': '已发货',
    'completed': '已完成',
    'cancelled': '已取消',
    'refunded': '已退款'
  }
  return statusMap[status] || status
}

// 获取订单状态样式类
const getStatusClass = (status) => {
  const classMap = {
    'pending': 'status-pending',
    'paid': 'status-paid',
    'shipped': 'status-shipped',
    'completed': 'status-completed',
    'cancelled': 'status-cancelled',
    'refunded': 'status-refunded'
  }
  return classMap[status] || ''
}

// 计算订单总价
const getOrderTotal = (order) => {
  return order.products.reduce((total, product) => total + product.price, 0)
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return ''
  
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  
  return `${year}-${month}-${day} ${hours}:${minutes}`
}

// 查看订单详情
const viewOrderDetail = (id) => {
  uni.showToast({
    title: '功能开发中',
    icon: 'none'
  })
}

// 支付订单
const payOrder = (id) => {
  uni.showModal({
    title: '支付提示',
    content: '确定要支付该订单吗？',
    success: (res) => {
      if (res.confirm) {
        // 找到对应订单
        const orderIndex = ordersList.value.findIndex(order => order.id === id)
        if (orderIndex !== -1) {
          // 更新订单状态
          ordersList.value[orderIndex].status = 'paid'
          
          // 更新Store中的订单状态
          userStore.updateOrderStatus(id, 'paid')
          
          // 提示
          uni.showToast({
            title: '支付成功',
            icon: 'success'
          })
        }
      }
    }
  })
}

// 确认收货
const confirmReceipt = (id) => {
  uni.showModal({
    title: '确认提示',
    content: '确定已收到商品吗？',
    success: (res) => {
      if (res.confirm) {
        // 找到对应订单
        const orderIndex = ordersList.value.findIndex(order => order.id === id)
        if (orderIndex !== -1) {
          // 更新订单状态
          ordersList.value[orderIndex].status = 'completed'
          
          // 更新Store中的订单状态
          userStore.updateOrderStatus(id, 'completed')
          
          // 提示
          uni.showToast({
            title: '已确认收货',
            icon: 'success'
          })
        }
      }
    }
  })
}

// 跳转到模板列表
const navigateToTemplates = () => {
  uni.switchTab({
    url: '/pages/template/list'
  })
}
</script>

<style lang="scss" scoped>
.order-page {
  min-height: 100vh;
  background-color: #F8F8F8;
  
  .content {
    padding: 16px;
    padding-top: 0;
  }
  
  .tabs {
    display: flex;
    background-color: #FFFFFF;
    border-radius: 12px;
    margin: 16px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
    overflow: hidden;
    
    .tab-item {
      flex: 1;
      height: 44px;
      display: flex;
      align-items: center;
      justify-content: center;
      position: relative;
      
      text {
        font-size: 14px;
        color: #666;
      }
      
      &.active {
        text {
          color: #5ac725;
          font-weight: 500;
        }
        
        &:after {
          content: '';
          position: absolute;
          left: 50%;
          bottom: 0;
          transform: translateX(-50%);
          width: 20px;
          height: 3px;
          background-color: #5ac725;
          border-radius: 3px;
        }
      }
    }
  }
  
  .orders-list {
    .order-item {
      background-color: #FFFFFF;
      border-radius: 12px;
      margin-bottom: 16px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
      overflow: hidden;
      
      .order-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 12px 16px;
        border-bottom: 1px solid #f5f5f5;
        
        .order-no {
          font-size: 14px;
          color: #666;
        }
        
        .order-status {
          font-size: 14px;
          
          &.status-pending {
            color: #ff9800;
          }
          
          &.status-paid {
            color: #5ac725;
          }
          
          &.status-shipped {
            color: #1e88e5;
          }
          
          &.status-completed {
            color: #9e9e9e;
          }
          
          &.status-cancelled {
            color: #f44336;
          }
          
          &.status-refunded {
            color: #f44336;
          }
        }
      }
      
      .order-products {
        padding: 12px 16px;
        
        .product-item {
          display: flex;
          align-items: center;
          margin-bottom: 12px;
          
          &:last-child {
            margin-bottom: 0;
          }
          
          .product-image {
            width: 60px;
            height: 60px;
            border-radius: 4px;
            margin-right: 12px;
          }
          
          .product-info {
            flex: 1;
            
            .product-name {
              font-size: 15px;
              color: #333;
              margin-bottom: 4px;
              display: block;
            }
            
            .product-desc {
              font-size: 13px;
              color: #999;
              display: block;
            }
          }
          
          .product-price {
            font-size: 16px;
            color: #333;
            font-weight: 500;
          }
        }
      }
      
      .order-footer {
        padding: 12px 16px;
        border-top: 1px solid #f5f5f5;
        
        .order-meta {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 12px;
          
          .order-time {
            font-size: 13px;
            color: #999;
          }
          
          .order-total {
            font-size: 15px;
            color: #333;
            font-weight: 500;
          }
        }
        
        .order-actions {
          display: flex;
          justify-content: flex-end;
          
          .action-btn {
            height: 32px;
            padding: 0 16px;
            border: 1px solid #ddd;
            border-radius: 16px;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-left: 12px;
            
            text {
              font-size: 14px;
              color: #666;
            }
            
            &.detail-btn {
              background-color: #f5f5f5;
              border-color: #f5f5f5;
            }
          }
        }
      }
    }
  }
  
  .empty-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 60px 0;
    
    .empty-icon {
      width: 140px;
      height: 140px;
      margin-bottom: 16px;
    }
    
    .empty-text {
      font-size: 16px;
      color: #999;
      margin-bottom: 20px;
    }
    
    .browse-btn {
      padding: 10px 20px;
      background-color: #5ac725;
      border-radius: 20px;
      
      text {
        color: #FFFFFF;
        font-size: 15px;
      }
    }
  }
}
</style> 